package com.example.shop.service;

import com.example.shop.dao.OrderDao;
import com.example.shop.entity.Order;
import com.example.shop.entity.Products;
import com.example.shop.model.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * author: adnaan
 * create: 2023-11-07 15:58
 * Description:
 */
@Service
public class OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public ApiResponse orderPage(Integer currentPage, Integer pageSize, String userId) {
        return orderDao.Paginated(currentPage,pageSize,userId);
    }

    public ApiResponse orderAdd(Order order) {
        Criteria criteriaName = Criteria.where("id").is(order.getProduct_id());
        Criteria orCriteria = new Criteria();
        orCriteria.orOperator(criteriaName);
        Query query = new Query(orCriteria);
        Products products = orderDao.get(query);
        order.setTotal_price(order.getQuantity()*products.getPrice());
        order.setStatus("待处理");
        LocalDateTime now = LocalDateTime.now();
        //格式化输出
        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        String format = now.format(dateTimeFormatter);
        order.setPurchase_date(format);
        Double productQuantity = stringRedisTemplate.opsForZSet().score("product", order.getProduct_id());
        if (productQuantity == null) {
            stringRedisTemplate.opsForZSet().add("product", order.getProduct_id(), +order.getQuantity());
        }else{
            stringRedisTemplate.opsForZSet().incrementScore("product", order.getProduct_id(), +order.getQuantity());
        }
        return orderDao.save(order);
    }
}
